package com.base.common.listener;

import android.os.FileObserver;
import android.support.annotation.Nullable;
import android.util.Log;

public class SDCardFileObserver extends FileObserver {
    private static final String TAG = "SDCardFileObserver";
    private FileChangeNotify fileChangeNotify;

    private String path;

    public SDCardFileObserver(String path, FileChangeNotify fileChangeNotify) {
        super(path);
        this.path = path;
        this.fileChangeNotify = fileChangeNotify;
    }

    public SDCardFileObserver(String path, int mask, FileChangeNotify fileChangeNotify) {
        super(path, mask);
        this.path = path;
        this.fileChangeNotify = fileChangeNotify;
    }

    @Override
    public void onEvent(int event, @Nullable String path) {
        final int action = event & FileObserver.ALL_EVENTS;
        //fileChangeNotify.notify(action, path);
        switch (action) {
            case FileObserver.ACCESS:
                //System.out.println("event: 文件或目录被访问, path: " + path);
                break;
            case FileObserver.CREATE:{
                Log.i(TAG, String.format("event: 文件或目录被创建, path:%s ", path));
                fileChangeNotify.notify(action, path);
                break;
            }
            case FileObserver.DELETE:{
                Log.i(TAG, String.format("event: 文件或目录被删除, path:%s ", path));
                fileChangeNotify.notify(action, path);
                break;
            }case FileObserver.OPEN:
              //  Log.i(TAG, String.format("event: 文件或目录被打开, path:%s ", path));
                break;
            case FileObserver.MODIFY:
               // Log.i(TAG, String.format("event: 文件或目录被修改, path:%s ", path));
                break;
        }
    }

    /**
     * 文件改变通知
     */
    public interface FileChangeNotify{
        /**
         * 通知方法
         * @param action 文件改变方式。 See: FileObserver: [ACCESS ,DELETE,OPEN,MODIFY]
         * @param path  文件路径
         */
        void notify(int action, String path);
    }
}
